<template>
  <div id="announcementInfo" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="/announcement/announcement">公告/提醒</BreadcrumbItem>
			</Breadcrumb>
			<div class="btns">
				<ButtonGroup>
          <Button type="text" @click="openModal"><i class="fa fa-plus"></i><span>添加</span></Button>
	        <Button type="text" @click="exportData"><i class="fa fa-download"></i><span>导出数据</span></Button>
	    	</ButtonGroup>
			</div>
		</div>
    <TableSearch>
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <FormItem label="提醒内容">
              <Input v-model="searchForm.content" placeholder="关键字模糊查询" />
		        </FormItem>
          </Col>
          <Col :md="8">
            <FormItem label="发送时间">
              <DatePicker v-model="dateRange" type="daterange" placement="bottom-end" placeholder="请选择"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search" long>查询</Button>
		</TableSearch>

    <div class="table-content">
			<div class="table">
				<table>
					<thead>
						<th>提醒内容</th>
						<th>发送时间</th>
						<th>接收对象</th>
						<th>是否发送</th>
					</thead>
					<tbody>
            <tr v-for="(v,i) in pageData.thisPageElements" :key="`Announcement-list-key-${v.id}`">
							<td :title="v.msgContent">{{v.msgContentStr}}</td>
							<td>{{v.sendTimeStr}}</td>
							<td>{{v.receiveUniqueName}}</td>
							<td class="operate">
								<a v-if="v.isSend===0" @click="doSendMsg(v.id)">发送</a>
                <span v-if="v.isSend===1">已发送</span>
							</td>
						</tr>
            <tr v-if="!isLoading && pageData.totalNumberOfElements <= 0">
              <td colspan="4">暂无数据</td>
            </tr>
					</tbody>
				</table>
			</div>

			<Page :total="pageData.totalNumberOfElements" :page-size="pageData.pageSize" :current="current" @on-change="loadPage" show-total></Page>
			<Spin size="large" fix v-if="isLoading"></Spin>
		</div>

    <Modal v-model="modal" :title="title" @on-visible-change="vchange" width="500">
      <Form :label-width="80" :model="form" ref="form" :rules="rules">
        <Row :gutter="16">
          <Col :md="24">
            <FormItem label="提醒内容" prop="msgContent">
              <Input v-model="form.msgContent" type="textarea" :autosize="{minRows: 3,maxRows: 5}" :maxlength="200" placeholder="请输入提醒内容"></Input>
       			</FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :md="24">
            <FormItem label="接收对象" prop="targetId">
              <div style="line-height:1.2">
                <Input v-model="form.targetId" style="display:none" />
                <Tree :data="treeData" :load-data="loadData" ref="tree" @on-select-change="treeSelect" multiple></Tree>
              </div>
       			</FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="text" @click="closeModal">取消</Button>
        <Button type="primary" :loading="isSubmiting" @click="doAdd(0)">保存</Button>
        <Button type="primary" :loading="isSubmiting" @click="doAdd(1)">保存并发送</Button>
      </div>
    </Modal>

  </div>
</template>

<script>
  import {mapState,mapActions} from 'vuex'
  import moment                from 'moment'
  import {download,post}  		 from '@/util/request'
  import _ from 'lodash'

  export default {
    components:{
    },
    data(){
      return {

        dateRange: [],
        searchForm:{
          content:'',
          sTime:'',
          eTime:''
        },
        // 提交时使用
        submitForm:{},

        form:{msgContent:'',isSend:0, targetId:'', json:''},
        rules:{
          msgContent:{required: true, message: '提醒内容', trigger: 'change'},
  				targetId:{required:true, message:'请至少选择一个推送项', trigger:'change'}
        },

        current:1,
        modal:false,
        title:'新增提醒',

        //封装机构树
        lowerOrgs:null,
        treeData:[],
        selectedData:[]
      };
    },
    watch: {
      dateRange([sTime,eTime]) {
        this.searchForm.sTime = sTime ? moment(sTime).format('YYYY-MM-DD') : '';
        this.searchForm.eTime = eTime ? moment(eTime).format('YYYY-MM-DD') : '';
      }
    },
    computed:{
      ...mapState('announcement/announcementList',['isLoading','pageData','isModalLoading','isSubmiting']),
      ...mapState('base',['userinfo'])
    },
    methods:{
      moment,
      ...mapActions('announcement/announcementList',['reload','add','sendMsg']),
      search(){
        this.submitForm = {...this.searchForm};
        this.loadPage(1);
			},
      loadPage(n){
				this.current = n;
				this.reload({
					pageNum:this.current,
					...this.submitForm
				});
			},
      async doSendMsg(id){
        this.$Modal.confirm({
          title: '提醒',
          content: `是否发送提醒？`,
          loading: true,
          onOk:async ()=>{
            let res = await this.sendMsg(id);
            if(res.data.success){
              this.$Modal.remove();
              this.loadPage(this.current);
              this.$Message.success('发送成功');
            }else{
              this.$Modal.remove();
              this.$Message.error(res.data.msg);
            }
          }
        });
      },
      exportData(){
        download('/base/announcement/export',this.submitForm);
      },
      openModal(){
        this.modal = true;
      },
      closeModal(){
        this.modal = false;
      },
      createTreeList(pid){
        let ary = [];
        this.lowerOrgs.forEach(o => {
          if (o.parentId === pid) {
            o.children = this.createTreeList(o.id);
            ary.push(o);
          }
        });
        return ary;
      },
      async loadData (item, callback) {
        let res = await post('/common/findDriverByOrgId', {orgIds:item.id});
        let json = res.data;
        if (json.sta === 200) {
          let data = [];
          json.data.map(o => {
            let it = {};
            it.title=o.name;
            it.id=o.id;
            it.receiveType=1;
            it.parentId=o.orgId;
            data.push(it);
          });
          callback(data);
        }
      },
      treeSelect(nodes){
        let ary = nodes;
        if(nodes.length===1){
          this.selectedData = [...ary];
        } else {
          let nodeLen = nodes.length;
          let selectedLen = this.selectedData.length;
          if(nodeLen>selectedLen){// 增加了选中项
            // 把新增的项找到。
            let diffs = _.difference(ary,this.selectedData);
            let diffObj = diffs[0];

            if(diffObj.receiveType===2){//选中机构，清除所有下级选中状态，且清除selectedData
              diffObj.children.forEach((o)=>{
                o.selected = false;
              });
              _.remove(this.selectedData,function(o){return _.indexOf(diffObj.children,o)!==-1; });
            } else {//选中驾驶员，清除父级选中状态，且清除selectedData
              this.selectedData.forEach((o)=>{
                if(o.id===diffObj.parentId){
                  o.selected = false;
                }
              });
              _.remove(this.selectedData,function(o){return o.id===diffObj.parentId});
            }
            this.selectedData.push(diffObj);
          } else {// 减少了选中项
            let diffs = _.difference(this.selectedData,ary);
            let diffObj = diffs[0];
            _.remove(this.selectedData,function(o){return o.id===diffObj.id;});
          }
        }

				let lst = [];
        let jsonLst = [];
        this.selectedData.forEach((v) => {
          lst.push(v.id);
          let o = {};
          o.receiveUniqueId = v.id;
          o.receiveUniqueName = v.title;
          o.receiveType = v.receiveType;
          jsonLst.push(o);
        });
				this.form.targetId = lst.join(',');
        this.form.json = JSON.stringify(jsonLst);
			},
      async doAdd(t){// t=0保存/未推送，t=1保存并提交/已推送
        let v = await this.$refs.form.validate();
        if(v){
          this.form.isSend = t;
          let res = await this.add(this.form);
          if(res.data.success){
            this.closeModal();
            this.current = 1;
            this.loadPage(this.current);
            this.$Message.success('保存成功');
          }else{
            this.$Message.error(res.data.msg);
          }
        }
      },
      vchange(e){
        if(!e){
          this.$refs.form.resetFields();
          this.form = {msgContent:'',isSend:0, targetId:'', json:''};
          this.selectedData = [];
          let items = this.$refs.tree.getSelectedNodes();
          items.forEach(o=>{o.selected = false;})
        }
      }
    },
    mounted(){
      this.reload();
      let orgs = [];
      this.userinfo.lowerOrgs.forEach(function(item,index,arr){
        let o = {...item};
        let it = {};
        it.title = o.orgName;
        it.id = o.id;
        it.parentId = o.parentId;
        it.expand = o.orgType !== 2;
        it.disabled = o.orgType !== 2;
        it.loading = false;
        it.receiveType=2;
        orgs.push(it);
      });
      this.lowerOrgs = orgs;
      this.treeData = this.createTreeList(this.userinfo.org.parentId);
    }
  }
</script>
